package com.sf.entity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogParser {

    public static void main(String[] args) {
        String folderPath = "C:\\Users\\hcf\\work\\文档\\demo\\日志\\轨迹"; // 替换为你的文件夹路径
        String outputPath = "C:\\Users\\hcf\\work\\文档\\demo\\日志\\轨迹.txt"; // 替换为输出文件路径

        try {
            File folder = new File(folderPath);
            File[] listOfFiles = folder.listFiles((dir, name) -> name.toLowerCase().endsWith(".txt"));

            if (listOfFiles != null) {
                List<JSONObject> logDataList = new ArrayList<>();
                for (File file : listOfFiles) {
                    if (file.isFile()) {
                        String logData = readFile(file.getAbsolutePath());
                        List<JSONObject> extractedData = extractJsonFromLog(logData);
                        logDataList.addAll(extractedData);
                    }
                }
                writeToFile(outputPath, logDataList);
            } else {
                System.out.println("文件夹中没有找到txt文件。");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取文件内容
    public static String readFile(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                content.append(line).append("\n");
            }
        }
        return content.toString();
    }

    // 提取请求参数后的JSON字符串
    public static List<JSONObject> extractJsonFromLog(String logData) {
        //告警和设备
        String regex = "requetst: (\\[\\[.*?\\]\\])";
        //
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(logData);

        List<JSONObject> logDataList = new ArrayList<>();
        while (matcher.find()) {
            String jsonStr = matcher.group(1);
            JSONArray jsonArray = new JSONArray(jsonStr);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONArray innerArray = jsonArray.getJSONArray(i);
                for (int j = 0; j < innerArray.length(); j++) {
                    JSONObject jsonObject = innerArray.getJSONObject(j);
                    logDataList.add(jsonObject);
                }
            }
        }
        return logDataList;
    }

    // 将结果写入文件
    public static void writeToFile(String filePath, List<JSONObject> data) throws IOException {
        JSONArray jsonArray = new JSONArray(data);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(jsonArray.toString(4)); // 格式化输出
        }
    }
}
